package cn.netswap.jeegorilla.framework.security.config;

import cn.netswap.jeegorilla.framework.security.consts.SecurityConstants;
import cn.netswap.jeegorilla.framework.security.handler.GorillaAuthenticationFailureHandler;
import cn.netswap.jeegorilla.framework.security.handler.GorillaAuthenticationSuccessHandler;
import cn.netswap.jeegorilla.framework.security.handler.GorillaLogoutSuccessHandler;
import cn.netswap.jeegorilla.framework.security.service.GorillaUserDetailsService;
import cn.netswap.jeegorilla.framework.security.social.SocialConfigurer;
import cn.netswap.jeegorilla.framework.security.strategy.GorillaExpiredSessionStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

/**
 * @author lgw
 * @version 1.0
 * @date 2020/3/18 14:21
 */
@Configuration
@EnableWebSecurity
public class GorillaSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private SocialConfigurer gorillaSocialConfigurer;

    @Autowired
    private InvidCodeAuthenticationSecurityConfig invidCodeAuthenticationSecurityConfig;

    @Autowired
    private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;

    @Autowired
    private GorillaAuthenticationSuccessHandler gorillaAuthenticationSuccessHandler;

    @Autowired
    private GorillaAuthenticationFailureHandler gorillaAuthenticationFailureHandler;

    @Autowired
    GorillaLogoutSuccessHandler gorillaLogoutSuccessHandler;

    @Autowired
    private GorillaUserDetailsService  gorillaUserDetailsService;

    @Autowired
    private DataSource dataSource;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .apply(gorillaSocialConfigurer).and()
                    // 配置需要认证的请求
                    .authorizeRequests()
                    .antMatchers(SecurityConstants.ignoreUris).permitAll()
                    .anyRequest()
                    .authenticated()
                .and()
                    .apply(invidCodeAuthenticationSecurityConfig)
                .and()
                    .apply(smsCodeAuthenticationSecurityConfig)
                .and()
                // 登录表单相关配置
                .formLogin()
                    .loginProcessingUrl("/login")
                    .loginPage("/loginPage")
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .successHandler(gorillaAuthenticationSuccessHandler)
                    .failureHandler(gorillaAuthenticationFailureHandler)
                    .permitAll()
                .and()
                    .rememberMe()
                    .tokenRepository(persistentTokenRepository())
                .and()
                // 登出相关配置
                    .logout()
                    .logoutSuccessHandler(gorillaLogoutSuccessHandler)
                    .deleteCookies("JSESSIONID")
                    .permitAll()
                .and()
                    .sessionManagement()
                    .invalidSessionUrl("/sessionInvaid")
                    //设置并发登录
                    .maximumSessions(1)
                    .expiredSessionStrategy(new GorillaExpiredSessionStrategy());

    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);

        return tokenRepository;
    }


    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/static/**");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(gorillaUserDetailsService).passwordEncoder(passwordEncoder());
    }

}
